<template>
  <div class="search-result-page">
    <div class="search-header">
      <h2>搜索结果：“{{ keyword }}”</h2>
      <p v-if="totalCount > 0">找到 {{ totalCount }} 个相关咖啡产品</p>
      <p v-else class="no-result">未找到相关商品，请尝试其他关键词</p>
    </div>

    <div class="product-list" v-loading="loading">
      <div class="product-card" v-for="product in productList" :key="product.id">
        <div class="product-img">
          <el-image
            :src="getImageUrl(product.image_urls)"
            :preview-src-list="getPreviewImages(product.image_urls)"
            fit="cover"
            placeholder="暂无图片"
          ></el-image>
        </div>
        <div class="product-info">
          <h3 class="product-name">{{ product.name }}</h3>
          <p class="product-desc" v-if="product.description">
            {{ product.description.length > 50
              ? `${product.description.slice(0, 50)}...`
              : product.description
            }}
          </p>
          <div class="product-price">
            <span class="original-price" v-if="product.original_price">
              ¥{{ product.original_price.toFixed(2) }}
            </span>
            <span class="current-price">¥{{ product.price.toFixed(2) }}</span>
          </div>
          <div class="product-stock">库存：{{ product.stock }} 件</div>
          <div class="product-tag" v-if="product.is_recommend">
            <el-tag type="success" size="mini">推荐</el-tag>
          </div>
          <!-- 新增：加入购物车按钮（与查看详情并排） -->
          <div class="product-actions">
            <el-button type="default" size="small" @click="addToCart(product)" :disabled="product.stock <= 0">
              <i class="fa fa-shopping-cart"></i> 加入购物车
            </el-button>
            <el-button type="primary" size="small" @click="goToDetail(product.id)">
              查看详情
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <div class="pagination" v-if="totalCount > 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import api from '@/api/request'

export default {
  name: 'CoffeeSearchResult',
  data() {
    return {
      loading: false,
      productList: [],
      totalCount: 0,
      keyword: '',
      currentPage: 1,
      pageSize: 10
    }
  },
  created() {
    this.keyword = this.$route.query.keyword || ''
    this.currentPage = Number(this.$route.query.page) || 1
    this.pageSize = Number(this.$route.query.limit) || 10
    this.fetchCoffeeSearch()
  },
  watch: {
    // 监听路由的 query 参数（关键词、页码等变化都会触发）
    '$route.query': {
      // 当 query 变化时执行的回调
      handler(newQuery, oldQuery) {
        // 1. 对比关键参数是否真的变化（避免无意义的重复请求）
        console.log(11111)
        console.log("newQuery", newQuery)
        console.log("oldQuery", oldQuery)
        if (
          newQuery.keyword !== oldQuery.keyword ||
          newQuery.page !== oldQuery.page ||
          newQuery.limit !== oldQuery.limit
        ) {
          // 2. 重新提取新的路由参数
          this.extractUrlParams()
          // 3. 重新执行搜索逻辑
          console.log("重新执行搜索")
          this.fetchCoffeeSearch()
        }
      },
      // Vue2 必须加 deep: true 才能监听对象内部属性变化（如 query.keyword）
      deep: true
    }
  },
  methods: {
    extractUrlParams() {
      const query = this.$route.query
      console.log("=== 从URL提取的原始参数 ===", query)

      this.keyword = query.keyword ? query.keyword.trim() : ''
      this.currentPage = query.page ? Number(query.page) : 1
      this.pageSize = query.limit ? Number(query.limit) : 10

      console.log("=== 转换后的参数 ===")
      console.log("keyword:", this.keyword, "(类型:", typeof this.keyword, ")")
      console.log("currentPage:", this.currentPage, "(类型:", typeof this.currentPage, ")")
      console.log("pageSize:", this.pageSize, "(类型:", typeof this.pageSize, ")")
    },
    // 原有方法完全不变
    async fetchCoffeeSearch() {
      this.loading = true;
      try {
        const params = {
          keyword: this.keyword || undefined,
          page: Number(this.currentPage),
          limit: Number(this.pageSize),
          is_puton: "true",
          is_recommend: undefined
        };
        const validParams = Object.fromEntries(
          Object.entries(params).filter(([_, v]) => v !== undefined)
        );
        const res = await api.get('/coffeeProduct/search', { params: validParams });
        if (res.code === 200) {
          this.productList = res.data.coffee_products || [];
          this.totalCount = res.data.pagination.total || 0;
          console.log("咖啡商品列表：", this.productList);
        } else {
          this.$message.error(res.message || '咖啡搜索失败');
        }
      } catch (err) {
        console.error('咖啡搜索请求错误：', err);
        this.$message.error('网络或服务器异常，请稍后再试');
      } finally {
        this.loading = false;
      }
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.$router.push({
        path: '/coffee-search-result',
        query: { keyword: this.keyword, page, limit: this.pageSize }
      })
      this.fetchCoffeeSearch()
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.$router.push({
        path: '/coffee-search-result',
        query: { keyword: this.keyword, page: 1, limit: size }
      })
      this.fetchCoffeeSearch()
    },
    getImageUrl(imageUrls) {
      if (!imageUrls || imageUrls.length === 0) {
        return ''
      }
      const firstImg = imageUrls[0]
      return firstImg.startsWith('http')
        ? firstImg
        : `http://127.0.0.1:8000/static/${firstImg}`
    },
    getPreviewImages(imageUrls) {
      if (!imageUrls || imageUrls.length === 0) return []
      return imageUrls.map(img =>
        img.startsWith('http') ? img : `http://127.0.0.1:8000/static/${img}`
      )
    },
    goToDetail(productId) {
      this.$router.push(`/coffee-detail/${productId}`)
    },

    // 新增：加入购物车方法（不影响原有逻辑）
    async addToCart(product) {
      try {
        await api.post('/cart', {
          product_id: product.id,
          product_type: 'merchandise',
          quantity: 1
        })
        alert("已成功添加至购物车")
        window.location.reload();
      } catch (e) {
        console.error('422 错误详情：', e.response?.data);
        console.error('添加失败', e);
      }
    },
  }
}
</script>

<style scoped>
/* 保持与周边搜索页一致的基础样式 */
.search-result-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

/* 搜索头部样式 */
.search-header {
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}
.search-header h2 {
  font-size: 18px;
  color: #3D2314;
  margin: 0 0 8px 0;
  font-weight: 600;
}
.search-header p {
  margin: 0;
  font-size: 14px;
}
.search-header .no-result {
  color: #E63946;
  font-weight: 500;
}

/* 商品列表网格 */
.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

/* 商品卡片样式 */
.product-card {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
  background: white;
  box-shadow: 0 2px 6px rgba(0,0,0,0.05);
}

/* 商品图片样式 */
.product-img {
  width: 100%;
  height: 180px;
}
.el-image {
  width: 100%;
  height: 100%;
}
.el-image__inner {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.el-image__placeholder {
  background-color: #f8f8f8;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

/* 商品信息区域 */
.product-info {
  padding: 15px;
  position: relative;
}

/* 商品名称 */
.product-name {
  font-size: 16px;
  color: #333;
  margin: 0 0 10px 0;
  font-weight: 500;
  white-space: normal;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.5;
}

/* 商品描述 */
.product-desc {
  font-size: 13px;
  color: #666;
  margin: 0 0 12px 0;
  line-height: 1.4;
}

/* 价格样式 */
.product-price {
  margin: 0 0 10px 0;
}
.original-price {
  text-decoration: line-through;
  color: #999;
  font-size: 12px;
  margin-right: 8px;
}
.current-price {
  color: #E63946;
  font-size: 16px;
  font-weight: 600;
}

/* 库存样式 */
.product-stock {
  font-size: 12px;
  color: #666;
  margin: 0 0 15px 0;
}

/* 推荐标签 */
.product-tag {
  position: absolute;
  top: 15px;
  right: 15px;
}

/* 新增：按钮区域样式（两个按钮并排） */
.product-actions {
  display: flex;
  gap: 8px;  /* 按钮间距 */
}
/* 加入购物车按钮样式 */
.product-actions .el-button--default {
  flex: 1;  /* 两个按钮均分宽度 */
  background-color: #f8f8f8;
  color: #333;
  border-color: #ddd;
}
.product-actions .el-button--default:disabled {
  background-color: #f8f8f8;
  color: #ccc;
  cursor: not-allowed;
}
/* 查看详情按钮样式 */
.product-actions .el-button--primary {
  flex: 1;  /* 两个按钮均分宽度 */
  background-color: #8B5A2B;
  border-color: #8B5A2B;
  color: white;
}
/* 按钮hover效果 */
.product-actions .el-button--default:hover:not(:disabled) {
  background-color: #f0f0f0;
  border-color: #ccc;
}
.product-actions .el-button--primary:hover {
  background-color: #6d4418;
  border-color: #6d4418;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .product-list {
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 15px;
  }
  .product-img {
    height: 160px;
  }
  /* 移动端按钮文字简化 */
  .product-actions .el-button--default span {
    display: none;
  }
  .product-actions .el-button--default::before {
    content: "加入购物车";
    font-size: 12px;
  }
}
@media (max-width: 480px) {
  .product-list {
    grid-template-columns: 1fr;
  }
}
</style>